package com.qf.ability.message.entity;

import com.qf.commons.core.utils.ApplicationUtils;
import lombok.Data;
import lombok.experimental.Accessors;
import org.kurento.client.KurentoClient;
import org.kurento.client.MediaPipeline;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 房间
 * author Ken
 * create_time 2022/10/17
 */
@Data
@Accessors(chain = true)
public class Room implements Serializable {

    /**
     * 课程id - 作为房间id
     */
    private Integer cid;

    /**
     * 主播信息
     */
    private UserSession master;

    /**
     * 观看者
     */
    private Map<Integer, UserSession> slaves = new ConcurrentHashMap<>();

    /**
     * 媒体服务器的媒体通道
     */
    private MediaPipeline mediaPipeline = ApplicationUtils.getBean(KurentoClient.class).createMediaPipeline();

    /**
     * 是否开始直播
     */
    private boolean isPlayer = false;


    /**
     * 添加用户对象
     */
    public void addUser(UserSession session){
        if (session.getRole().equals("master")) {
            this.master = session;
        } else {
            this.slaves.put(session.getUid(), session);
        }
    }

    /**
     * 群发消息
     */
    public void sendAll(Message message, boolean master){
        if (master && this.master != null) {
            this.master.getChannel().writeAndFlush(message);
        }

        if (!CollectionUtils.isEmpty(slaves)) {
            for (UserSession slave : slaves.values()) {
                slave.getChannel().writeAndFlush(message);
            }
        }
    }
}
